package com.zxy.ider.ehome;

import java.io.File;
import java.text.DecimalFormat;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.ider.deskcust.TileEntry;
import com.zxy.ider.ehome.View.FlyImageView;
import com.zxy.ider.ehome.View.TvProgressBar;
import com.zxy.ider.ehome.adapter.HomeGridAdapter;
import com.zxy.ider.ehome.bean.Application;
import com.zxy.ider.ehome.util.ApplicationUtil;
import com.zxy.ider.ehome.util.NetUtil;
import com.zxy.ider.ehome.util.PreferenceManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

public class CommonApp extends Activity {
	boolean DEBUG = false;
	String TAG = "CommanApp";
	GridView grid;
	RelativeLayout mainRelative;
	FlyImageView fly;
	Handler handler = new Handler();
	DecimalFormat df = new DecimalFormat("0000");
	ImageView screen_move;
	ImageView screen_keep;
	ImageView img_dim;
	private TileEntry[] tiles;
	private int gridwidth;
	private static final long DEFAULT_TRAN_DUR_BIG_ANIM = 150;
	private static final long DEFAULT_TRAN_DUR_SMALL_ANIM = 50;
	private View lastSelected;
	private PreferenceManager pmanager;
	private boolean isfirst = false;
	private int y=0;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.common_apps);
		mainRelative = (RelativeLayout) findViewById(R.id.main_relative);
		grid = (GridView) findViewById(R.id.detail_grid);
		fly = (FlyImageView) findViewById(R.id.mainUpView1);
		pmanager= PreferenceManager.getInstance(this);
		Intent intent = getIntent();
		y = intent.getIntExtra("keep", 0);
		String data = intent.getStringExtra("json");
		screen_move = (ImageView) findViewById(R.id.image_move);
		screen_keep = (ImageView) findViewById(R.id.image_keep);
		img_dim = (ImageView) findViewById(R.id.image_dim);

		initData(data);
	}

	public void initData(String data){
		if (HomeActivity.move!=null&&!HomeActivity.move.isRecycled())
			screen_move.setImageBitmap(HomeActivity.move);
		if (HomeActivity.keep!=null&&!HomeActivity.keep.isRecycled())
			screen_keep.setImageBitmap(HomeActivity.keep);
		screen_keep.setY(y);
		mainRelative.setY(y - Constant.commonAppTranLength);

		TranslateAnimation tranAnim = new TranslateAnimation(0, 0, 0,
				-Constant.commonAppTranLength);
		tranAnim.setDuration(300);
		tranAnim.setFillAfter(true);
		screen_move.startAnimation(tranAnim);
		tranAnim.setAnimationListener(new MyAnimationListener());
		try {
			JSONArray jarray = new JSONArray(data);
			tiles = new TileEntry[jarray.length()];
			for(int i = 0;i<jarray.length();i++){
				tiles[i]=new TileEntry(jarray.getJSONObject(i));
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		setCenterGrid(tiles.length);
		grid.setAdapter(new HomeGridAdapter(tiles));
		grid.setSelector(new ColorDrawable(Color.TRANSPARENT));
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				if (grid.getChildAt(0) != null) {
					fly.setVisibility(View.VISIBLE);
					fly.flyTo(fly.getWidth(), fly.getHeight(),
							grid.getChildAt(0).getLeft()+getleftMargin()+getResources().getDimensionPixelOffset(R.dimen.px25),
							getResources().getDimensionPixelOffset(R.dimen.px410));
					grid.getChildAt(0).animate().scaleX(1.11f).scaleY(1.11f).setDuration(DEFAULT_TRAN_DUR_BIG_ANIM).start();
				}
			}
		}, 200);
		setListeners();
	}

	/*设置GridView居中显示
  *
          * @param size
  *            元素个数
  */
	public void setCenterGrid(int size) {
		if (size <= 5)
			grid.setNumColumns(size);
		else if (size > 5)
			grid.setNumColumns(5);
		gridwidth = getWrapWidth(size)+120;
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
				gridwidth, getResources().getDimensionPixelSize(R.dimen.px550));
		params.addRule(RelativeLayout.CENTER_IN_PARENT);
		grid.setLayoutParams(params);
	}


	public int getWrapWidth(int size) {

		int item_width = getResources().getDimensionPixelSize(
				R.dimen.px400);
		int horizontal_space = getResources().getDimensionPixelSize(
				R.dimen.px80);
		if (size == 1) {
			return item_width;
		} else if (size > 1 && size <= 5) {
			return item_width * size + horizontal_space * (size - 1);
		} else if (size > 5) {
			return getWrapWidth(5);
		}

		return 0;
	}


	@Override
	protected void onPause() {
		super.onPause();
		try {
		} catch (Exception e) {

		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
	}

	class MyAnimationListener implements AnimationListener {

		@Override
		public void onAnimationEnd(Animation arg0) {
			System.out.println("anim end");

			AlphaAnimation alphaAnim = new AlphaAnimation(0.0f, 1.0f);
			alphaAnim.setDuration(300);
			alphaAnim.setFillAfter(true);
			alphaAnim.setAnimationListener(new DimAnimationListener());
			img_dim.startAnimation(alphaAnim);
			mainRelative.bringToFront();

		}

		@Override
		public void onAnimationRepeat(Animation arg0) {

		}

		@Override
		public void onAnimationStart(Animation arg0) {

		}

	}

	class DimAnimationListener implements AnimationListener {

		@Override
		public void onAnimationEnd(Animation arg0) {
			img_dim.setVisibility(View.VISIBLE);
		}

		@Override
		public void onAnimationRepeat(Animation arg0) {

		}

		@Override
		public void onAnimationStart(Animation arg0) {

		}

	}

	class ExitAlphaAnimationListener implements AnimationListener {
		boolean isexit = false;
		String data;
		public ExitAlphaAnimationListener(boolean isexit,String data) {
			this.isexit = isexit;
			this.data =data;
		}

		public ExitAlphaAnimationListener() {
		}

		@Override
		public void onAnimationEnd(Animation arg0) {

			screen_move.bringToFront();
			img_dim.bringToFront();
			TranslateAnimation exitAnim = new TranslateAnimation(0, 0,
					-Constant.commonAppTranLength, 0);
			exitAnim.setDuration(500);
			exitAnim.setFillAfter(true);
			exitAnim.setAnimationListener(new ExitTranAnimationListener(isexit,data));
			screen_move.startAnimation(exitAnim);
		}

		@Override
		public void onAnimationRepeat(Animation arg0) {

		}

		@Override
		public void onAnimationStart(Animation arg0) {

		}

	}

	class ExitTranAnimationListener implements AnimationListener {
		boolean isexit = false;
		String data;

		public ExitTranAnimationListener(boolean isexit, String data) {
			this.isexit = isexit;
			this.data = data;
		}

		public ExitTranAnimationListener() {
		}

		@Override
		public void onAnimationEnd(Animation arg0) {
			if(isexit) {
				CommonApp.this.finish();
				CommonApp.this.overridePendingTransition(0, 0);
			}else{
				initData(data);
			}
		}

		@Override
		public void onAnimationRepeat(Animation arg0) {

		}

		@Override
		public void onAnimationStart(Animation arg0) {

		}

	}

	public void setListeners() {
		grid.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				TileEntry tile = tiles[position];
				TvProgressBar progressBar = (TvProgressBar) view.findViewById(R.id.tpb_ring);
				Log.i(TAG, "onItemClick: position===="+position);
				openItem(CommonApp.this,progressBar,tile);

			}
		});

		grid.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {

				if (view == null) {
					return;
				}
				if (lastSelected != null) {
					lastSelected.animate().scaleX(1f).scaleY(1f).setDuration(DEFAULT_TRAN_DUR_SMALL_ANIM).start();
				} else {
					grid.getChildAt(0).animate().scaleX(1f).scaleY(1f).setDuration(DEFAULT_TRAN_DUR_SMALL_ANIM).start();
				}
				int[] locations = new int[2];
				view.getLocationOnScreen(locations);
				fly.bringToFront();
				view.animate().scaleX(1.11f).scaleY(1.11f).setDuration(DEFAULT_TRAN_DUR_BIG_ANIM).start();
				fly.flyTo(fly.getWidth(), fly.getHeight(),
						view.getLeft()+getleftMargin()+getResources().getDimensionPixelOffset(R.dimen.px25),
						getResources().getDimensionPixelOffset(R.dimen.px410));
				lastSelected = view;
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});


	}

	public int getleftMargin(){
		WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
		int width = wm.getDefaultDisplay().getWidth();
		int left = (width-gridwidth)/2;

		Log.i(TAG, "getleftMargin: left = "+left+"*****width="+width);
		return left;
	}


	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK
				) {
			AlphaAnimation exitAlpha = new AlphaAnimation(1.0f, 0.0f);
			exitAlpha.setDuration(200);
			exitAlpha.setFillAfter(true);
			exitAlpha.setAnimationListener(new ExitAlphaAnimationListener(true,null));
			img_dim.startAnimation(exitAlpha);
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}


	public  void  openItem(Activity activity, TvProgressBar progress, TileEntry tile){
		Log.i(TAG, "openItem: ---------------"+tile.strutype);
		switch (tile.strutype){
			case "app":
				Log.i(TAG, "openItem: url =="+tile.apkaddress);
				Application app = ApplicationUtil.doApplication(Appcontext.getAppContext(),tile.strucommand);
				if(app==null) {
					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
						isfirst = pmanager.isFirstRun();
						if (isfirst) {
							ActivityCompat.requestPermissions(CommonApp.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
						}
					} else {
						File cacheFolder = new File(Constant.APK_CACHE_PATH);
						if (!cacheFolder.exists()) {
							Log.i(TAG, "openItem: file not exit");
							boolean s1 = cacheFolder.mkdirs();
							Log.i(TAG, "openItem: file =" + cacheFolder.exists() + s1);
						}
					}
					showUpdateDialog(activity, tile.apkaddress, progress);
				}else{
					ApplicationUtil.startApp(Appcontext.getAppContext(),app);
				}
				break;
			case "web":
				Intent intent = new Intent();
				intent.setAction("android.intent.action.VIEW");
				Uri content_url = Uri.parse(tile.strucommand);
				intent.setData(content_url);
				startActivity(intent);
				break;
			case "interface":
				AlphaAnimation exitAlpha = new AlphaAnimation(1.0f, 0.0f);
				exitAlpha.setDuration(200);
				exitAlpha.setFillAfter(true);
				exitAlpha.setAnimationListener(new ExitAlphaAnimationListener(false,tile.stru));
				img_dim.startAnimation(exitAlpha);
				//data
//				grid.removeAllViews();

				break;
			case "local":
				Toast.makeText(CommonApp.this,"打开文件管理器",Toast.LENGTH_SHORT).show();
				break;
		}
	}

	@SuppressLint("SdCardPath")
	public void showUpdateDialog(final Activity activity, final String url, final TvProgressBar progress){
		final AlertDialog.Builder normalDialog =
				new AlertDialog.Builder(activity);
		normalDialog.setIcon(R.mipmap.ic_launcher);
		normalDialog.setTitle(activity.getResources().getString(R.string.downappTitle));
		normalDialog.setMessage("          MESSAGE:     "+activity.getResources().getString(R.string.downapp));
		normalDialog.setPositiveButton(activity.getResources().getString(R.string.btn_enter),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						//...To-do
						Log.i(TAG, "onClick: url =="+url);
						startDownload(Constant.APK_CACHE_PATH,url,activity,progress);
						Toast.makeText(activity, "开始下载", Toast.LENGTH_SHORT).show();
						dialog.dismiss();
						dialog.cancel();
					}
				});
		normalDialog.setNegativeButton(activity.getResources().getString(R.string.Cancel),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						//...To-do
						dialog.dismiss();
						dialog.cancel();
					}
				});
		normalDialog.show();

	}


	public void startDownload(final String path, String url, final Activity activity, final TvProgressBar loadingbar){
		RequestParams requestParams = new RequestParams(url);
		requestParams.setSaveFilePath(path+"/"+ NetUtil.getNameFromUrl(url));
		x.http().get(requestParams, new Callback.ProgressCallback<File>() {

			@Override
			public void onCancelled(CancelledException arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {
				// TODO Auto-generated method stub
				Toast.makeText(activity, "下载失败，请检查网络和SD卡", Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onFinished() {
				// TODO Auto-generated method stub

			}

			@Override
			public void onSuccess(File file) {
				// TODO Auto-generated method stub
				Toast.makeText(activity, "下载成功,开始安装", Toast.LENGTH_SHORT).show();
				Intent intent = new Intent(Intent.ACTION_VIEW);
				Log.i(TAG, "onSuccess: file=="+file.getAbsolutePath());
				intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
				activity.startActivity(intent);
				//InstallUtil.installSlient(LAUNCHER_INSTALL_PATCH);
				loadingbar.setVisibility(View.GONE);
			}

			@Override
			public void onLoading(long total, long current, boolean isDownloading) {
				loadingbar.setVisibility(View.VISIBLE);
				int progress = (int) (current*100/total);
				loadingbar.setProgress(progress);
			}

			@Override
			public void onStarted() {
				// TODO Auto-generated method stub

			}

			@Override
			public void onWaiting() {
				// TODO Auto-generated method stub

			}

		});
	}
}
